<template>
  <cl-dialog v-model="visible" class="zhongtian-add-order" width="90%" :close-on-click-modal="false">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <span>中天系统订单添加</span>
        </div>
      </template>
      <el-button @click="syncGoods">同步商品</el-button>
      <el-form ref="formRef" :model="formData" label-width="120px">
        
        <!-- 验光数据（可选） -->
        <el-divider content-position="left">验光数据</el-divider>
        
        <el-row :gutter="20">
          
          <el-col :span="12">
            <el-form-item label="左球镜" prop="data.o.c_lball">
              <el-input v-model="formData.c_lball" placeholder="请输入左球镜" />
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="右球镜" prop="data.o.c_rball">
              <el-input v-model="formData.c_rball" placeholder="请输入右球镜" />
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="左柱镜" prop="data.o.c_lpole">
              <el-input v-model="formData.c_lpole" placeholder="请输入左柱镜" />
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="右柱镜" prop="data.o.c_rpole">
              <el-input v-model="formData.c_rpole" placeholder="请输入右柱镜" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-button @click="getGoodsList(formData.c_lball, formData.c_lpole, 'left')">查询左镜片</el-button>
            <el-select v-if="c_goods_left_list.length > 0" v-model="formData.c_goods_l" placeholder="请选择镜片">
              <el-option v-for="item in c_goods_left_list" :key="item.id" :label="item.c_breedname" :value="item.id" />
            </el-select>
          </el-col>

          <el-col :span="12">
            <el-button @click="getGoodsList(formData.c_rball, formData.c_rpole, 'right')">查询右镜片</el-button>
            <el-select v-if="c_goods_right_list.length > 0" v-model="formData.c_goods_r" placeholder="请选择镜片">
              <el-option v-for="item in c_goods_right_list" :key="item.id" :label="item.c_breedname" :value="item.id" />
            </el-select>
          </el-col>
        </el-row>
        <!-- 操作按钮 -->
        <div class="form-actions">
          <el-button type="primary" @click="submitForm">提交订单</el-button>
          <el-button @click="resetForm">重置</el-button>
          <el-button @click="closeDialog">关闭</el-button>
        </div>
      </el-form>
    </el-card>
  </cl-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, defineExpose, watch } from 'vue';
import { ElMessage } from 'element-plus';
import { useCool } from '/@/cool';
import { useI18n } from 'vue-i18n';

const { service } = useCool();
const { t } = useI18n();
const formRef = ref();
const visible = ref(false);
const emit = defineEmits(['closeDialog', 'update:modelValue',]);

const props = defineProps({
  orderId: {
    type: Number,
    default: 0
  },
  modelValue: {
        type: Boolean,
        default: false
    }
})

// 表单数据
const formData = reactive({
    c_lball: '+0.25',
    c_rball: '+0.75',
    c_lpole: '+0',
    c_rpole: '-0.25',
    c_goods_l: '',
    c_goods_r: '',
    c_goods_left_list: [],
    c_goods_right_list: [],
    order_id: props.orderId
});
const c_goods_left_list = ref([])
const c_goods_right_list = ref([])

// 获取商品列表
async function getGoodsList(c_ball, c_pole, type) {
  const res = await service.order.merchant.getGoodsList({
    c_ball,
    c_pole
  })
  if (res.length <= 0) {
    ElMessage.error('没有符合要求的镜片')
    return
  }
    if (type == 'left') {
        c_goods_left_list.value = res
    } else if (type == 'right') {
        c_goods_right_list.value = res
    }
  
  console.log('获取商品列表', res)
}

// 提交表单
async function submitForm() {
  if (!formRef.value) return;
  
  try {
    await formRef.value.validate();
    
    // 这里是提交表单的逻辑，调用API提交数据
    console.log('提交的表单数据:', formData);
    if (formData.c_goods_l == '' || formData.c_goods_r == '') {
        ElMessage.error('请选择镜片')
        return
    }
    formData.order_id = props.orderId
    // 模拟API调用
    // 实际项目中应替换为真实的API调用
    const res = await service.order.merchant.submitOrder(formData);
    console.log(res)
    // 模拟提交成功
    ElMessage.success('订单添加成功');
    
    // 关闭弹窗
    closeDialog();
  } catch (error) {
    console.error('表单验证失败:', error);
    ElMessage.error(error.message);
  }
}

// 重置表单
function resetForm() {
  if (formRef.value) {
    formRef.value.resetFields();
    // 重置普通字段
    formData.c_lball = '';
    formData.c_rball = '';
    formData.c_lpole = '';
    formData.c_rpole = '';
  }
}

// 关闭弹窗
function closeDialog() {
    console.log('props.currentOrderId', props.orderId, visible.value)
    emit('closeDialog')
}

async function syncGoods() {
  const res = await service.order.merchant.getGoodsType()
  console.log(res);
}

// 监听 modelValue 变化
watch(
	() => props.modelValue,
	val => {
        console.log('弹窗', val, props.orderId)
        if (val) {
            // getGoodsList()
        }
		visible.value = val;
	}
);

// 监听 visible 变化
watch(
	() => visible.value,
	val => {
		emit('update:modelValue', val);
		if (!val) {
			resetForm();
		}
	}
);

// 添加验光数据变化监听器，重置对应镜片列表
watch(
  () => [formData.c_lball, formData.c_lpole],
  ([newLball, newLpole], [oldLball, oldLpole]) => {
    if (newLball !== oldLball || newLpole !== oldLpole) {
      // 左球镜或左柱镜变化时，重置左镜片列表
      formData.c_goods_left_list = [];
      formData.c_goods_l = '';
      console.log('左验光数据已修改，已重置左镜片列表');
    }
  },
  { immediate: false }
);

watch(
  () => [formData.c_rball, formData.c_rpole],
  ([newRball, newRpole], [oldRball, oldRpole]) => {
    if (newRball !== oldRball || newRpole !== oldRpole) {
      // 右球镜或右柱镜变化时，重置右镜片列表
      formData.c_goods_right_list = [];
      formData.c_goods_r = '';
      console.log('右验光数据已修改，已重置右镜片列表');
    }
  },
  { immediate: false }
);

</script>

<style scoped>
.zhongtian-add-order {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.detail-item,
.payment-item {
  margin-bottom: 20px;
}

.detail-header,
.payment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.border-top-blue {
  border-top: 3px solid #409eff;
}

.form-actions {
  margin-top: 30px;
  text-align: center;
}

.form-actions .el-button {
  margin: 0 10px;
}
</style>